<?php

namespace app\api\controller;

use app\api\BaseController;
use app\model\Gift as GiftModel;
use app\model\Message as MessageModel;
use app\model\User as UserModel;
use think\App;

class Chat extends BaseController
{
    public function getOnLineList()
    {
        $ret = curlHelper("http://127.0.0.1:9999");
        $arr = json_decode($ret['body'], true);
        $userModel = new UserModel();
        $ret = $userModel->field('user_id,user_name,user_head,user_plat,user_login,user_group')->where([
            ['user_id', 'in', $arr],
        ])->select();
        // $ret = $userModel ->field('user_id,user_name,user_head,user_plat,user_login,user_group')->orderRand()->limit(rand(40,100))->select();
        // $ret = $userModel ->field('user_id,user_name,user_head,user_plat,user_login,user_group')->limit(rand(70,82))->select();
        for ($i = 0; $i < count($ret); $i++) {
            $ret[$i]['isMaster'] = in_array($ret[$i]['user_group'], [1, 6]) ? 1 : 0;
        }
        return jok('success', $ret);
    }
    public function getRankList()
    {
        $type = input('type');
        switch ($type) {
            case 'gift_get':
                $giftModel = new GiftModel();
                $ret = $giftModel->view('gift')->field('count(gift_to) as user_gift')
                    ->order('user_gift desc,user_id desc')->view('user', 'user_id,user_name,user_head,user_plat,user_login,user_group', 'gift.gift_to = user.user_id')->group('gift_to')->limit(50)->select();
                return jok('success', $ret);
                break;
            case 'gift_send':
                $giftModel = new GiftModel();
                $ret = $giftModel->view('gift')->field('count(gift_user) as user_gift')
                    ->order('user_gift desc,user_id desc')->view('user', 'user_id,user_name,user_head,user_plat,user_login,user_group', 'gift.gift_user = user.user_id')->group('gift_user')->limit(50)->select();
                return jok('success', $ret);
                break;
            case 'chat':
                $messageModel = new MessageModel();
                $ret = $messageModel->view('message')->field('count(message_user) as user_message')
                    ->order('user_message desc,user_id desc')->view('user', 'user_id,user_name,user_head,user_plat,user_login,user_group', 'message.message_user = user.user_id')->group('message_user')->limit(50)->select();
                return jok('success', $ret);
                break;
            case 'picture':
                $messageModel = new MessageModel();
                $ret = $messageModel->view('message')->field('count(message_user) as user_message')
                    ->order('user_message desc,user_id desc')->view('user', 'user_id,user_name,user_head,user_plat,user_login,user_group', 'message.message_user = user.user_id')->where('message_type', 'img')->group('message_user')->limit(50)->select();
                return jok('success', $ret);
                break;
            case 'song':
                $userModel = new UserModel();
                $ret = $userModel->field('user_id,user_name,user_head,user_plat,user_login,user_group,user_song')
                    ->order('user_song desc,user_id desc')->where('user_song', '>', 0)->limit(50)->select();
                return jok('success', $ret);
                break;
            default:
        }
        return jok('success', []);
    }
    public function search()
    {
        $arr = [];
        if (input("keyword")) {
            $keyword = input('keyword');
            $html = curlHelper("https://www.doutula.com/search?keyword=" . urlencode($keyword))['body'];
            $html = str_replace(PHP_EOL, '', $html);
            $html = str_replace(' ', '', $html);
            $html = str_replace('　', '', $html);
            $arr = [];
            if (preg_match_all('/<imgreferrerpolicy="no-referrer"src=".*?"data-backup="(.*?)"/', $html, $match)) {
                // print_r($match[0]);
                foreach ($match[1] as $item) {
                    if (count($arr) >= 20) {
                        break;
                    }
                    array_push($arr, $item);
                }
            }
        }
        return jok('', $arr);
    }
    public function searchSong()
    {
        $arr = [];
        if (input("keyword")) {
            $keyword = input('keyword');
            $res = curlHelper("https://c.y.qq.com/soso/fcgi-bin/client_search_cp?n=50&new_json=1&format=json&w=" . urlencode($keyword));
            $data = json_decode($res['body'], true);
            if ($data['code'] == 0 && array_key_exists('song', $data['data'])) {
                $list = [];
                foreach ($data['data']['song']['list'] as $song) {
                    $singers = [];
                    foreach ($song['singer'] as $singer) {
                        array_push($singers, [
                            'id' => $singer['id'],
                            'mid' => $singer['mid'],
                            'name' => $singer['name'],
                        ]);
                    }
                    array_push($list, [
                        'id' => $song['id'],
                        'mid' => $song['mid'],
                        'name' => $song['name'],
                        'singer' => $singers,
                    ]);
                }
                return jok('', $list);
            }
        }
        return jok('', []);
    }
    public function getNowSong()
    {
        $song = cache('SongNow');
        $user = null;
        if ($song) {
            $userModel = new UserModel();
            $user = $userModel->field('user_id,user_name,user_head,user_plat,user_login,user_group')->where('user_id', $song['user'])->find();
        }
        return jok('success', [
            'song' => $song,
            'user' => $user,
        ]);
    }
    public function pickSong()
    {
        $error = $this->access();
        if ($error) {
            return $error;
        }
        if (!input('singer')) {
            return jerr("singer参数为必传");
        }

        $singer = input('singer');
        if (!input('name') || !input('mid')) {
            return jerr("请选择歌曲后点歌");
        }

        $name = input('name');
        $mid = input('mid');

        $res = curlHelper("https://u.y.qq.com/cgi-bin/musicu.fcg?format=json&data=%7B%22req_0%22%3A%7B%22module%22%3A%22vkey.GetVkeyServer%22%2C%22method%22%3A%22CgiGetVkey%22%2C%22param%22%3A%7B%22guid%22%3A%22358840384%22%2C%22songmid%22%3A%5B%22" . $mid . "%22%5D%2C%22songtype%22%3A%5B0%5D%2C%22uin%22%3A%221443481947%22%2C%22loginflag%22%3A1%2C%22platform%22%3A%2220%22%7D%7D%2C%22comm%22%3A%7B%22uin%22%3A%2218585073516%22%2C%22format%22%3A%22json%22%2C%22ct%22%3A24%2C%22cv%22%3A0%7D%7D");
        $data = json_decode($res['body'], true);
        if ($data['code'] == 0 && array_key_exists('req_0', $data) && array_key_exists('data', $data['req_0']) && array_key_exists('midurlinfo', $data['req_0']['data']) && array_key_exists('sip', $data['req_0']['data']) && array_key_exists('testfilewifi', $data['req_0']['data'])) {
            $music = $data['req_0']['data'];
            $url = $music['sip'][0];
            if (count($music['midurlinfo']) > 0 && array_key_exists('purl', $music['midurlinfo'][0])) {
                if (!$music['midurlinfo'][0]['purl']) {
                    return jerr('因版权原因该歌曲无法被点歌！');
                }
            } else {
                return jerr('因版权原因该歌曲无法被点歌！');
            }
        } else {
            return jerr('因版权原因该歌曲无法被点歌！');
        }

        if (!in_array($this->user['user_group'], [1, 6, 7])) {
            if (cache('song_' . $this->user['user_id'])) {
                return jerr('点歌太频繁，请一分钟后再试');
            }
        }
        cache('song_' . $this->user['user_id'], $mid, 60);

        $songList = cache('SongList') ?? '';
        $songList = json_decode($songList, true) ?? [];
        $existSong = null;
        foreach ($songList as $item) {
            if ($item['mid'] == $mid && $item['user'] == $this->user['user_id']) {
                $existSong = $item['name'];
            }
        }
        if ($existSong) {
            return jerr('你已经点过歌曲《' . $existSong . '》');
        }
        array_push($songList, [
            'mid' => $mid,
            'name' => $name,
            'user' => $this->user['user_id'],
        ]);
        cache('SongList', json_encode($songList), 86400);
        $user = [
            'user_id' => $this->user['user_id'],
            'user_name' => $this->user['user_name'],
            'user_plat' => $this->user['user_plat'],
            'user_login' => $this->user['user_login'],
            'user_head' => $this->user['user_head'],
        ];
        $msg = json_encode([
            'song' => [
                'mid' => $mid,
                'name' => $name,
                'singer' => $singer,
            ],
            "user" => $user,
            "type" => "pick",
            "time" => date('H:i:s'),
        ]);
        $ret = curlHelper("http://127.0.0.1:9999", "POST", http_build_query([
            'token' => getWebsocketSign(),
            'channel' => getWebsocketChannel(),
            'msg' => $msg,
        ]), [
            'content-type:application/x-www-form-urlencode',
        ]);
        $userModel = new UserModel();
        $userModel->where('user_id', $this->user['user_id'])->inc('user_song')->update();
        return jok('歌曲' . $name . '已经添加到播放列表！');
    }
    public function pushSong()
    {
        $error = $this->access();
        if ($error) {
            return $error;
        }
        if (!input('mid')) {
            return jerr("mid参数为必传");
        }
        $mid = input('mid');

        $songList = cache('SongList') ?? '';
        $songList = json_decode($songList, true) ?? [];
        $pushSong = false;
        for ($i = 0; $i < count($songList); $i++) {
            $item = $songList[$i];
            if ($item['mid'] == $mid) {
                $pushSong = $item;
                unset($songList[$i]);
                array_unshift($songList, $item);
                break;
            }
        }
        if (!$pushSong) {
            return jerr("顶歌失败，歌曲ID不存在");
        }

        $pushCount = 5;
        $pushCache = cache('push_' . date('Ymd') . '_' . $this->user['user_id']);
        $pushCache = $pushCache ? intval($pushCache) : 0;
        if ($pushCache >= $pushCount) {
            if (!in_array($this->user['user_group'], [1, 6, 7])) {
                return jerr("你今日的" . $pushCount . "次顶歌机会已使用完啦");
            }
        }
        $pushCache++;
        cache('push_' . date('Ymd') . '_' . $this->user['user_id'], $pushCache, 86400);

        cache('SongList', json_encode($songList), 86400);
        $user = [
            'user_id' => $this->user['user_id'],
            'user_name' => $this->user['user_name'],
            'user_plat' => $this->user['user_plat'],
            'user_login' => $this->user['user_login'],
            'user_head' => $this->user['user_head'],
        ];
        $msg = json_encode([
            'song' => $pushSong,
            "user" => $user,
            "type" => "push",
            "time" => date('H:i:s'),
        ]);
        $ret = curlHelper("http://127.0.0.1:9999", "POST", http_build_query([
            'token' => getWebsocketSign(),
            'channel' => getWebsocketChannel(),
            'msg' => $msg,
        ]), [
            'content-type:application/x-www-form-urlencode',
        ]);
        if (!in_array($this->user['user_group'], [1, 6, 7])) {
            return jok('顶歌成功,今日剩余' . ($pushCount - $pushCache) . '次顶歌机会!');
        }
        return jok('顶歌成功');
    }
    public function getMusicUrl()
    {
        if (!input('mid')) {
            return jerr('参数错误');
        }
        $mid = input('mid');
        $res = curlHelper("https://u.y.qq.com/cgi-bin/musicu.fcg?format=json&data=%7B%22req_0%22%3A%7B%22module%22%3A%22vkey.GetVkeyServer%22%2C%22method%22%3A%22CgiGetVkey%22%2C%22param%22%3A%7B%22guid%22%3A%22358840384%22%2C%22songmid%22%3A%5B%22" . $mid . "%22%5D%2C%22songtype%22%3A%5B0%5D%2C%22uin%22%3A%221443481947%22%2C%22loginflag%22%3A1%2C%22platform%22%3A%2220%22%7D%7D%2C%22comm%22%3A%7B%22uin%22%3A%2218585073516%22%2C%22format%22%3A%22json%22%2C%22ct%22%3A24%2C%22cv%22%3A0%7D%7D");
        $data = json_decode($res['body'], true);
        if ($data['code'] == 0 && array_key_exists('req_0', $data) && array_key_exists('data', $data['req_0']) && array_key_exists('midurlinfo', $data['req_0']['data']) && array_key_exists('sip', $data['req_0']['data']) && array_key_exists('testfilewifi', $data['req_0']['data'])) {
            $music = $data['req_0']['data'];
            $url = $music['sip'][0];
            if (count($music['midurlinfo']) > 0 && array_key_exists('purl', $music['midurlinfo'][0])) {
                if (!$music['midurlinfo'][0]['purl']) {
                    return jerr('因版权原因该歌曲无法播放！');
                }
                $url .= $music['midurlinfo'][0]['purl'];
            } else {
                return jerr('因版权原因该歌曲无法播放！');
            }
            return jok($url);
        } else {
            return jerr('因版权原因该歌曲无法播放！');
        }
    }
    public function getBackMessage()
    {
        $error = $this->access();
        if ($error) {
            return $error;
        }
        if (!input('sha') || !input('key')) {
            return jerr('参数错误');
        }
        $sha = input('sha');
        $key = input('key');
        if ($sha != sha1($key . "_" . $this->user['user_id']) && !in_array($this->user['user_group'], [1, 6])) {
            return jerr('你没有权限撤回别人的消息');
        }

        $user = [
            'user_id' => $this->user['user_id'],
            'user_name' => $this->user['user_name'],
            'user_plat' => $this->user['user_plat'],
            'user_login' => $this->user['user_login'],
            'user_head' => $this->user['user_head'],
        ];
        $msg = json_encode([
            "user" => $user,
            "message_sha" => $sha,
            "type" => "back",
            "time" => date('H:i:s'),
        ]);
        $ret = curlHelper("http://127.0.0.1:9999", "POST", http_build_query([
            'token' => getWebsocketSign(),
            'channel' => getWebsocketChannel(),
            'msg' => $msg,
        ]), [
            'content-type:application/x-www-form-urlencode',
        ]);
        return jok('撤回消息成功!');
    }
    public function nextSong()
    {
        $error = $this->access();
        if ($error) {
            return $error;
        }
        $now = cache('SongNow') ?? '';
        $time = cache('SongNextTime') ?? 0;
        if (!$now) {
            return jerr('当前没有正在播放的歌曲');
        }
        if (time() - $time < 10) {
            return jerr('切歌太频繁，请稍候再试。');
        }
        cache('SongNextTime', time());
        // $songList = cache('SongList') ?? '';
        // $songList = json_decode($songList, true) ?? [];
        // if (count($songList) == 0) {
        //     return jerr('没有更多的歌曲啦，快一起来点歌吧~');
        // }
        if (input('mid')) {
            if ($now['mid'] != input('mid')) {
                return jerr('切歌失败，你没有权限切掉这首歌');
            } else {
                cache('SongNow', null);
            }
        } else {
            if ($now['user'] != $this->user['user_id'] && !in_array($this->user['user_group'], [1, 6, 7])) {
                return jerr('仅管理员和点歌人可切歌呀~');
            }
            cache('SongNow', null);
            $user = [
                'user_id' => $this->user['user_id'],
                'user_name' => $this->user['user_name'],
                'user_plat' => $this->user['user_plat'],
                'user_login' => $this->user['user_login'],
                'user_head' => $this->user['user_head'],
            ];
            $msg = json_encode([
                "user" => $user,
                "type" => "next",
                "time" => date('H:i:s'),
            ]);
            $ret = curlHelper("http://127.0.0.1:9999", "POST", http_build_query([
                'token' => getWebsocketSign(),
                'channel' => getWebsocketChannel(),
                'msg' => $msg,
            ]), [
                'content-type:application/x-www-form-urlencode',
            ]);
        }
        return jok('切歌成功');
    }
    public function sendGift()
    {
        $error = $this->access();
        if ($error) {
            return $error;
        }
        if (!input('type')) {
            return jerr('你应该要告诉我送什么酒的呀');
        }
        if (!input('user')) {
            return jerr('你应该告诉我送给谁呀');
        }

        $userModel = new UserModel();

        $to = $userModel->field('user_id,user_name,user_head,user_plat,user_login,user_group')->where('user_id', input('user'))->find();
        if (!$to) {
            return jerr('查询用户信息失败');
        }
        if ($to['user_id'] == $this->user['user_id']) {
            return jerr('是有多想不开自己给自己送？？？');
        }

        $myGift = cache('GiftLast_' . $this->user['user_id']) ?? null;
        if ($myGift) {
            return jerr('送礼物太频繁，请稍候再试。');
        }
        // cache('GiftLast_' . $this->user['user_id'], time(), 5);
        cache('GiftLast_' . $this->user['user_id'], time(), 60);
        $giftModel = new GiftModel();
        $giftModel->insert([
            'gift_user' => $this->user['user_id'],
            'gift_to' => $to['user_id'],
            'gift_type' => input('type'),
            'gift_createtime' => time(),
        ]);
        $user = [
            'user_id' => $this->user['user_id'],
            'user_name' => $this->user['user_name'],
            'user_plat' => $this->user['user_plat'],
            'user_login' => $this->user['user_login'],
            'user_head' => $this->user['user_head'],
        ];
        $msg = json_encode([
            "user" => $user,
            "to" => $to,
            "gift" => input('type'),
            "type" => "gift",
            "time" => date('H:i:s'),
        ]);
        $ret = curlHelper("http://127.0.0.1:9999", "POST", http_build_query([
            'token' => getWebsocketSign(),
            'channel' => getWebsocketChannel(),
            'msg' => $msg,
        ]), [
            'content-type:application/x-www-form-urlencode',
        ]);
        return jok('送礼物成功！');
    }
    public function songList()
    {
        $songList = cache('SongList') ?? '';
        $songList = json_decode($songList, true) ?? [];
        $userModel = new UserModel();
        for ($i = 0; $i < count($songList); $i++) {
            $song = $songList[$i];
            $user = $userModel->field('user_id,user_name,user_head,user_plat,user_login,user_group')->where('user_id', $song['user'])->find();
            $songList[$i]['userInfo'] = $user;
        }
        return jok('', $songList ?? []);
    }
    public function getSongLrc()
    {
        if (!input('mid')) {
            return jerr('参数错误');
        }
        $mid = input('mid');
        $res = curlHelper("https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?songmid=" . $mid . "&format=json&inCharset=utf8&outCharset=utf-8", 'GET', null, [
            'referer: https://y.qq.com/portal/player.html',
        ]);
        $data = json_decode($res['body'], true);
        if ($data['code'] == 0 && $data['retcode'] == 0 && $data['subcode'] == 0) {
            return jok('', base64_decode($data['lyric']));
        } else {
            return jerr('没有查询到歌词');
        }
    }
}
